package com.jwdf.uda.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.jwdf.uda.ui.fragment.question.bean.NewAnswer;
import com.jwdf.uda.ui.fragment.question.bean.NewProblems;
import com.jwdf.uda.ui.fragment.user.bean.UserSession;
import com.jwdf.uda.update.AppUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/5/12.
 */
public class ConfigUtils {
    private static final String CONFIG_VER = "ver";
    private static final String PREFERENCE_NAME = "config";
    private static final String CURRENT_USER = "current_user";
    private static final String FOLLOW_COUNT = "followCount";
    private static final String NEW_ANSWER = "new_answer";
    private static final String NEW_PROBLEMS = "new_problems";
    private static final String SYSTEM_CONFIG = "system_config";
    private static final String PAGE_LENGTH = "page_length";
    private static final String MIDDLE_PAGE_LENGTH = "middle_page_length";
    private static final String ABOUT_PAGE = "about_page";
    private static final String USER_PROTOCOL = "user_protocol";
    private static final String HANDLE_INVALID = "handle_invalid";
    private static final String CHECK_HAS_PRIVACY_PERMISSION = "check_has_privacy_permission";
    private static final String HTTP_HEADERS_COOKIE = "http_headers_cookie";
    private static final String COOKIES = "cookies";
    private static final String IS_LAUNCH = "is_launch";
    private static final String TPL_REMIND = "tpl_remind";
    private static final String API_URL = "api_url";
    private static final String UPLOAD_URL = "upload_url";


    private static UserSession mCurrentUser;
    private static NewAnswer mNewAnswer;
    private static NewProblems mNewProblems;

    public static void setIsLaunch(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putBoolean(IS_LAUNCH, true);
        edit.commit();
    }

    private static SharedPreferences getSharedPreferences(Context context) {
        return getSharedPreferences(context, PREFERENCE_NAME);
    }

    private static SharedPreferences getSharedPreferences(Context context, String fileName) {
        return context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
    }

    public static boolean getIsLaunch(Context context) {
        return getSharedPreferences(context).getBoolean(IS_LAUNCH, false);
    }

    public static void setNoTPLRemind(Context context, boolean flag) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putBoolean(TPL_REMIND, flag);
        edit.commit();
    }

    public static boolean getIfNoTPLRemind(Context context) {
        return getSharedPreferences(context).getBoolean(TPL_REMIND, false);
    }

    public static void checkVer(Context context) {
        int currentVersion = AppUtils.getVersionCode(context);
        int ver = getSharedPreferences(context).getInt(CONFIG_VER, 0);
        if (ver < currentVersion) {
            setHttpHeadersCookie(context,"");
            SharedPreferences.Editor edit = getSharedPreferences(context).edit();
            edit.remove(CURRENT_USER);
            edit.putInt(CONFIG_VER, currentVersion);
            edit.commit();
        }
    }

    public static void setCurrentUser(Context context, UserSession user) {
        removeCurrentUser(context);
        Gson gson = new Gson();
        String userJson = gson.toJson(user);
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putString(CURRENT_USER, userJson);
        edit.commit();
    }

    public static void removeCurrentUser(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.remove(CURRENT_USER);
        edit.commit();
        mCurrentUser = null;
    }

    public static void setFollowCount(Context context, int followCount) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putInt(FOLLOW_COUNT, followCount);
        edit.commit();
    }

    public static void addFollowCount(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putInt(FOLLOW_COUNT, getFollowCount(context) + 1);
        edit.commit();
    }

    public static int getFollowCount(Context context) {
        int followCount = getSharedPreferences(context).getInt(FOLLOW_COUNT, 0);
        return followCount;
    }

    public static void reduceFollowCount(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putInt(FOLLOW_COUNT, getFollowCount(context) - 1);
        edit.commit();
    }

    public static void setNewAnswer(Context context, NewAnswer answer) {
        removeNewAnswer(context);
        Gson gson = new Gson();
        String userJson = gson.toJson(answer);
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putString(NEW_ANSWER + answer.getId(), userJson);
        edit.commit();
    }

    public static NewAnswer getNewAnswer(Context context, int id) {
        if (mNewAnswer == null) {
            String userJson = getSharedPreferences(context).getString(NEW_ANSWER + id, "");
            if (!TextUtils.isEmpty(userJson)) {
                Gson gson = new Gson();
                mNewAnswer = gson.fromJson(userJson, NewAnswer.class);
            }
        }
        return mNewAnswer;
    }

    public static void setNewProblems(Context context, NewProblems problems) {
        removeNewProblems(context);
        Gson gson = new Gson();
        String userJson = gson.toJson(problems);
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.putString(NEW_PROBLEMS, userJson);
        edit.commit();
    }

    public static NewProblems getNewProblems(Context context) {
        if (mNewProblems == null) {
            String userJson = getSharedPreferences(context).getString(NEW_PROBLEMS, "");
            if (!TextUtils.isEmpty(userJson)) {
                Gson gson = new Gson();
                mNewProblems = gson.fromJson(userJson, NewProblems.class);
            }
        }
        return mNewProblems;
    }

    public static void removeNewAnswer(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.remove(NEW_ANSWER);
        edit.commit();
        mNewAnswer = null;
    }

    public static void removeNewProblems(Context context) {
        SharedPreferences.Editor edit = getSharedPreferences(context).edit();
        edit.remove(NEW_PROBLEMS);
        edit.commit();
        mNewProblems = null;
    }

    public static String getSessionId(Context context) {
        UserSession user = getCurrentUser(context);
        if (user != null) {
            return user.getSessionId();
        }
        return "";
    }

    public static UserSession getCurrentUser(Context context) {
        if (mCurrentUser == null) {
            String userJson = getSharedPreferences(context).getString(CURRENT_USER, "");
            if (!TextUtils.isEmpty(userJson)) {
                Gson gson = new Gson();
                mCurrentUser = gson.fromJson(userJson, UserSession.class);
            }
        }
        return mCurrentUser;
    }

    public static String getToken(Context context) {
        UserSession user = getCurrentUser(context);
        if (user != null) {
            return user.getToken();
        }
        return "";
    }

    public static String getUserId(Context context) {
        UserSession user = getCurrentUser(context);
        if (user != null) {
            return user.getUserId();
        }
        return "";
    }

    public static boolean isStylist(Context context) {
        UserSession user = getCurrentUser(context);
        if (user != null) {
            return user.isStylist();
        }
        return false;
    }

    public static boolean isUserLogin(Context context) {
        return getCurrentUser(context) != null;
    }

    public static boolean saveStringArray(Context context, String fileName, List<String> source) {
        SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
        editor.clear();
        Set<String> set = new HashSet<>();
        List<String> newList = new ArrayList<>();
        for (Iterator iterator = source.iterator(); iterator.hasNext(); ) {
            String element = (String) iterator.next();
            if (set.add(element)) {
                newList.add(element);
            }
        }
        newList = new ArrayList<>(new LinkedHashSet(newList));
        for (int i = 0; i < newList.size(); i++) {
            editor.putString(String.valueOf(i), newList.get(i));
        }
        Log.i("fileName", "" + fileName + "");
        return editor.commit();
    }

    public static ArrayList<String> restoreStringArray(Context context, String fileName, boolean reverse) {
        String[] listArray = null;
        SharedPreferences preferences = getSharedPreferences(context, fileName);
        Map<String, ?> map = preferences.getAll();
        if (map != null && !map.isEmpty()) {
            listArray = new String[map.size()];
            for (Map.Entry<String, ?> entry : map.entrySet()) {
                try {
                    listArray[Integer.parseInt(entry.getKey())] = (String) entry.getValue();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
        ArrayList<String> newList = new ArrayList<>();
        if (listArray != null && listArray.length > 0) {
            ArrayList<String> list = new ArrayList<>(Arrays.asList(listArray));
            if (reverse) {
                Collections.reverse(list);
            }
            int size = list.size() >= 10 ? 10 : list.size();
            for (int i = 0; i < size; i++) {
                newList.add(list.get(i));
            }
        }
        return newList;
    }


    public static void setPageLength(Context context, int length) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putInt(PAGE_LENGTH, length);
        edit.commit();
    }

    public static int getPageLength(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getInt(PAGE_LENGTH, 10);
    }

    public static void setMiddlePageLength(Context context, int length) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putInt(MIDDLE_PAGE_LENGTH, length);
        edit.commit();
    }

    public static int getMiddlePageLength(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getInt(MIDDLE_PAGE_LENGTH, 20);
    }

    public static void setAboutPage(Context context, String aboutPage) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putString(ABOUT_PAGE, aboutPage);
        edit.commit();
    }

    public static String getAboutPage(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getString(ABOUT_PAGE, "");
    }

    public static void setUserProtocol(Context context, String aboutPage) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putString(USER_PROTOCOL, aboutPage);
        edit.commit();
    }

    public static String getUserProtocol(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getString(USER_PROTOCOL, "");
    }

    public static void setApiUrl(Context context, String apiUrl) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putString(API_URL, apiUrl);
        edit.commit();
    }

    public static String getApiUrl(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getString(API_URL, "");
    }

    public static void setUploadUrl(Context context, String apiUrl) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putString(UPLOAD_URL, apiUrl);
        edit.commit();
    }

    public static String getUploadUrl(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getString(UPLOAD_URL, "");
    }

    public static void setHandledInvalid(Context context, boolean handled) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putBoolean(HANDLE_INVALID, handled);
        edit.commit();
    }

    public static boolean isHandledInvalid(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getBoolean(HANDLE_INVALID, false);
    }

    public static void setRejectPrivacyPermission(Context context, boolean reject) {
        SharedPreferences.Editor edit = getSharedPreferences(context, SYSTEM_CONFIG).edit();
        edit.putBoolean(CHECK_HAS_PRIVACY_PERMISSION, reject);
        edit.commit();
    }

    public static boolean isRejectPrivacyPermission(Context context) {
        return getSharedPreferences(context, SYSTEM_CONFIG).getBoolean(CHECK_HAS_PRIVACY_PERMISSION, false);
    }

    public static void setHttpHeadersCookie(Context context, String cookie) {
        SharedPreferences.Editor edit = getSharedPreferences(context, COOKIES).edit();
        edit.putString(HTTP_HEADERS_COOKIE, cookie);
        edit.commit();
    }

    public static String getHttpHeadersCookie(Context context) {
        return getSharedPreferences(context, COOKIES).getString(HTTP_HEADERS_COOKIE, "");
    }

}
